package edu.sctu.zhuyingzhi.month201506.day20150628.theSecondTestV1;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.util.*;

/**
 * Created by user13 on 2015/6/23.
 */
public class ClientGetPostTest {

    static HttpClientBuilder builder = HttpClientBuilder.create();
    static CloseableHttpClient client = builder.build();


    public static void usePostRequests(String path,HashMap<String,String> map) {
        HttpPost postUrl = new HttpPost(path);

        List<BasicNameValuePair> postMsg = getPostMsg(map);


        UrlEncodedFormEntity urlEncoded;

        try {
            urlEncoded = new UrlEncodedFormEntity(postMsg, "utf-8");
            postUrl.setEntity(urlEncoded);

            HttpResponse response = client.execute(postUrl);
            HttpEntity entity = response.getEntity();

            InputStream inputStream = entity.getContent();
            String str = steamToString(inputStream);

            FileUtil.juageExist(FileUrl.Folder);

            FileOutputStream fileOutputStream = new FileOutputStream(new File(FileUrl.URL_json));
            fileOutputStream.write(str.getBytes());

            postUrl.releaseConnection();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 流变为字符串
     *
     * @param inputStream
     * @return
     * @throws java.io.IOException
     */
    public static String steamToString(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int count;
        String str = "";

        while ((count = inputStream.read(buffer)) != -1) {
            str = str + new String(buffer, 0, count, "utf-8");
        }
        return str;
    }

    public static List<BasicNameValuePair> getPostMsg(HashMap<String,String> map){
        Iterator iterator = map.entrySet().iterator();
        List<BasicNameValuePair> postMsg = new ArrayList<>();
        while(iterator.hasNext()){
            Map.Entry<String, String> entry= (Map.Entry<String, String>) iterator.next();
            postMsg.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        return postMsg;
    }
}
